import request from './request.js'
import lyric from './lyric.js'
import store from './store.js'

const api = 'https://api.i-meto.com/meting/api?'

/**
 * 获取数据
 * @param {*} id 
 * @param {*} server 
 * @param {*} type 
 */
function getMusic(id, server, type) {
  let url = api + 'server=' + server + '&type=' + type + '&id=' + id
  return request.get(url).then(function (response) {
    return Promise.resolve(response)
  })
}

/**
 * 获取歌单数据
 * @param {*} id 
 */
function getMusicList(id) {
  // 先缓存中获取
  let data = store.get(id)
  if (data === null) {
    console.log("get music list from request...")
    return this.getMusic(id, 'netease', 'playlist').then(function (response) {
      let list = parse(response)
      store.remove(id)
      store.set(id, list, 60 * 60 * 2) // 写入缓存，缓存时间 2 小时
      return Promise.resolve(list)
    })
  } else {
    console.log("get music list store...")
    return Promise.resolve(parse(data))
  }
}

/**
 * 获取缓存中的播放历史
 */
function getHistory() {
  return store.get('history')
}

/**
 * 将播放历史存入缓存
 * @param {*} history 
 */
function setHistory(history) {
  store.remove('history')
  store.set('history', history, 60 * 60 * 24) // 历史记录保存 1 天
}

/**
 * 解析歌曲信息（歌词解析）
 * @param {*} res 
 */
function parse(res) {
  let list = []
  for (let i = 0; i < res.length; i++) {
    let music = {}
    lyric.get(res[i].lrc).then((res) => {
      music.lyrics = res
    })
    music.author = res[i].author
    music.pic = res[i].pic
    music.title = res[i].title
    music.url = res[i].url
    music.lrc = res[i].lrc
    list.push(music)
  }
  return list
}

/**
 * 搜索
 * @param {*} server 
 * @param {*} keywords 
 */
function search(server, keywords) {
  return this.getMusic(keywords, server, 'search').then(function (response) {
    let list = parse(response)
    store.remove(keywords)
    store.set(keywords, list, 60 * 60 * 2) // 写入缓存，缓存时间 2 小时
    return Promise.resolve(list)
  }) 
}

module.exports = {
  getMusic,
  getMusicList,
  getHistory,
  setHistory,
  search
}